define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        uploader = require('js/utils/uploader'),
        app = Backbone.history;
    require('jquery-ui');
    require('magnific');
    require('datetimepicker');

    var CategoryListView = Backbone.View.extend({
        tagName: "div",
        className: "panel-body pn",
        events: {
            'click #categorySave': 'toSaveOrCreate',
            'click a.onClickDelete': "deleteItem",
        },
        initialize: function (options) {
            this.collection = new models.CategoryCollection();
            this.deletedImages = [];
            this.cachedImages = [];
            this.collection.bind('add remove change reset', this.renderWithData, this);
        },
        deleteItem: function (e) {
            e.preventDefault();
            var parent = $(e.currentTarget).parents('div.with-border'),
                url = parent.find("img.icon").attr('src'),
                id = parseInt(parent.data('id')),
                thisView = this;
            $(e.currentTarget).parents('div.with-border').remove();
            this.deletedImages.push(url);
            if (!isNaN(id) && id != -1) {
                $.ajax({
                    url: '/admin/category/' + id,
                    type: 'delete',
                    success: function () {
                        thisView.collection.remove(new models.Category({
                            id: id
                        }));
                        notify.success();
                    },
                    error: function (data) {
                        notify.notifyResp(data);
                    }
                });
            }
            return false;
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        getInputs: function () {
            var updatedItems = [];
            $('div.with-border').each(function (index) {
                var item = { order: index },
                    id = parseInt($(this).data('id'), 10);
                if (!isNaN(id) && id != -1) {
                    item.id = id;
                }
                item.icon = $(this).find('img').first().attr('src');
                if (!item.icon) {
                    notify.error('错误', '图片不存在');
                    return;
                }
                $(this).find('[data-field]').each(function () {
                    var v = $(this).val();
                    if ($(this).data('type') == 'timestamp') {
                        v = $(this).data('DateTimePicker').date().unix();
                    } else if ($(this).data('type') == 'int') {
                        v = parseInt(v);
                    }
                    item[$(this).data('field')] = v;
                });
                updatedItems.push(item);
            });
            _.each(this.cachedImages, function (img) {
                updatedItems.push({
                    icon: img,
                    name: "",
                    tag: "",
                    order: 0,
                    visibility: 1
                });
            });
            return updatedItems;
        },
        toSaveOrCreate: function (e) {
            e.preventDefault();
            var isAllRight = utils.simpleCheck();
            if (!isAllRight) {
                notify.error('错误', '输入错误，请检验');
                return;
            }
            this.collection.set(this.getInputs());
            this.collection.save({
                success: function () {
                    notify.success('提示', '保存成功！');
                    setTimeout(function () {
                        location.reload();
                    }, 500);
                },
                error: function (model, response) {
                    notify.notifyResp(response);
                }
            });
            if (this.deletedImages.length > 0)
                $.post('admin/image/delete/', {
                    urls: this.deletedImages.join(',')
                }).done(function () {
                    this.deletedImages = [];
                });
            return false;
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
            }));
            $('.sortable').sortable();
            $('.sortable').disableSelection();
            var that = this;
            $('#uploadIcon').magnificPopup({
                items: {
                    src: '#uploadImagePanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                // showCloseBtn: false,
                callbacks: {
                    beforeOpen: function () {
                        that.collection.set(that.getInputs());
                        uploader.getUploader('pickfiles', 'fsUploadProgress', function (url) {
                            that.cachedImages.push(url);
                        });
                        $('#addCachedImgs').off('click').click(function () {
                            that.collection.set(that.getInputs());
                            that.cachedImages = [];
                            $.magnificPopup.close();
                        });
                    }
                }
            });
            $('.replace-img').each(function () {
                var $this = $(this);
                uploader.getSingleUploader($this.attr('id'), function (url) {
                    that.deletedImages.push(url);
                });
            });
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/CategoryList.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new CategoryListView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});